package com.gufe.service.admin.impl;

import com.gufe.dto.SysUserDTO;
import com.gufe.dto.UserInfoDTO;
import com.gufe.entity.SysUser;
import com.gufe.mapper.AuthenticationMapper;
import com.gufe.mapper.admin.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements com.gufe.service.admin.LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private PasswordEncoder passwordEncoder; // 注入 BCryptPasswordEncoder

    @Autowired
    private AuthenticationMapper authenticationMapper;
    /**
     * 登录验证
     * @param sysUser
     * @return
     */
    public SysUser login(SysUserDTO sysUser) {
        // 1. 根据用户名查询数据库用户
        SysUser dbUser = authenticationMapper.selectUserByUsername(sysUser.getUsername());
        if (dbUser == null) {
            return null; // 用户不存在
        }

        // 2. 验证密码是否匹配
        if (!passwordEncoder.matches(sysUser.getPassword(), dbUser.getPassword())) {
            return null; // 密码错误
        }

        return dbUser; // 验证成功
    }

    /**
     * 查询用户角色信息
     *
     * @param id
     * @return
     */
    public UserInfoDTO getInfo(Integer id) {
        return new UserInfoDTO(loginMapper.getInfo(id));
    }

    @Override
    public Integer getRoleId(Integer id) {
        return loginMapper.getRoleId(id);
    }
}
